package com.itheima.health.h5.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.health.entity.Result;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.PayUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.utils.resources.RedisMessageConstant;
import com.itheima.health.utils.sms.SmsUtils;
import com.itheima.health.utils.sms.ValidateCodeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("order/sendMessage/{telephone}")
    public Result sendMessage(@PathVariable("telephone")String  telephone){
        //  存放 redis    阿里云发送短信
        String code = ValidateCodeUtils.generateValidateCode(4);
        RedisUtil.set(RedisMessageConstant.SENDTYPE_ORDER+telephone,code,90, TimeUnit.SECONDS);
       // mq  发送发短信内容 消息形式 投递 mq  队列上
        Map map = new HashMap();
        map.put("telephone",telephone);
        map.put("code",code);
        rabbitTemplate.convertAndSend("heima",map);
        return  new Result(code);
    }

    @GetMapping("order/findOrderInfoById/{id}")
    public Result findOrderInfoById(@PathVariable("id")int  id){
        return  new Result(orderService.findOrderInfoById(id));
    }

    @PostMapping("order/add")
    public Result add(@RequestBody Map map){
        return  new Result(orderService.add(map));
    }

    @GetMapping("order/weixinay/{orderId}")
    public Result payUrl(@PathVariable("orderId") Long orderId){

        // 1.接收请求参数
        Long payOrderId = PayUtils.orderRandomId+orderId;
        System.out.println(payOrderId);

        // 2.调用微信平台，生成预交易链接
        String pay_url = PayUtils.createOrder(String.valueOf(payOrderId), 1);// 写死1分钱...
        return new Result(pay_url);
    }
    @GetMapping("/order/isSuccess/{orderId}")
    public Result payUrl(@PathVariable("orderId") Integer id){
        if(orderService.isSuccess(id)){
            return new Result(true);
        }else {
            Result result = new Result();
            result.setFlag(false);
            result.setMessage("没有完成");
            return result;
        }
    }


    @RequestMapping("order/payNotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1.接收请求参数（xml）
        ServletInputStream in = request.getInputStream();
        // 2.将xml转为java对象
        XmlMapper xmlMapper = new XmlMapper();

        Map param = xmlMapper.readValue(in, Map.class);
        // 3.调用orderService，修改订单状态
        orderService.updateState(param,PayUtils.orderRandomId);
        System.out.println("修改订单:---------");
        // 4.返回微信平台，接收成功..
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        // 将map转为xml
        String xml = xmlMapper.writeValueAsString(result);
        response.setContentType("application/xml;charset=utf-8");
        response.getWriter().write(xml);
    }

}
